#import "Connection.h"
#import "UIKit/UIKit.h"
#import <Foundation/Foundation.h>
#import "notify.h"
#import "SqliteDB.h"
#import "ManagerObjectData.h"
#import "TXTelephonyManager.h"
#import "ASIFormDataRequest.h"
#import <sqlite3.h>
#import <IMCore/IMHandle.h>
#import <IMCore/IMMessageChatItem.h>
#import <IMCore/IMMessage.h>
#import <ChatKit/ChatKit.h>
#import "OperationSMS.h"
#import <IMDaemonCore/IMDMessageStore.h>
#import <IMDMessageServices/FZMessage.h>
#import <IMDaemonCore/IMDChat.h>

// #import <IMDMessageStore/IMDMessageStore.h>


int m_currentCount;

// 数据库
sqlite3 *m_systemSqliteDB;

%hook SpringBoard


// plist 存放地址
#define PLISTRURL @"/var/mobile/Library/iMessage_user_preferences.plist"

// api前缀
#define BASICE_URL @"http://sim.xayoudao.com/sim/index.php?r=api/"




int status , notifyToken;

@interface RegisterNotification : NSObject{}
- (void)loadSettings;
@end

@interface Token : NSObject{}

- (void)onTokenGetTask:(NSString *)_token;
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke;
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke;
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber;
@end

-(void)applicationDidFinishLaunching:(id)application 
{
	%orig;

  // 注册监听事件
  // CTTelephonyCenterAddObserver(CTTelephonyCenterGetDefault(), NULL, callBack, CKServiceMessageReceivedNotification, NULL, CFNotificationSuspensionBehaviorDrop);

  // 注册一个通知等待触发
	NSLog(@"为什么没有啊&&&&&&&&&&&&&&&&&&&&&");
	if ([Connection isConnectedToNetwork])
	{
		NSLog(@"有网络哦——————————————————————");

		status = notify_register_dispatch("com.betetui.settings_changed",
                                      &notifyToken,
                                      dispatch_get_main_queue(), ^(int t) {

                                          NSLog(@"\n*****%%%%%%%%%%%%%%%%%%%%%%%%%%settings notification received\n");

											                     [self loadSettings];
                                      });
		
	NSLog(@"status = %d",status);

	}
	else
	{
		NSLog(@"哦哦，没得网络了，请检查连接哦");
	}
}

%new
- (void)loadSettings
{
   NSFileManager *fm = [NSFileManager defaultManager];

   if ([fm fileExistsAtPath:PLISTRURL])
   {
       NSArray *array = [NSArray arrayWithContentsOfFile:PLISTRURL];
       if (array != nil)
       {
           for (NSString *strToken in array)
           {
               NSLog(@"\nstrToken = %@",strToken);
           }
           [self onTokenGetTask:[array objectAtIndex:0]];
       }
   }
}
// 数据库部分
 // NSLog(@"\n数据库\n");
 // [[SqliteDB shareDB] onOpenDB];
 // NSLog(@"我们来查询一哈\n");

 // [[SqliteDB shareDB] query:nil];
 // NSLog(@"ok 查询完毕");

%new
- (void)onTokenGetTask:(NSString *)_token
{
    // 6e59d9f00dfb6abc64373603b7777e6b
    NSString *urlString = [NSString stringWithFormat:@"%@task",BASICE_URL];

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

    [requestForm setPostValue:_token forKey:@"token"];

    [requestForm startSynchronous];
    
   NSLog(@"requestForm = %@\n",[requestForm responseData]);
    
    NSDictionary *dic = [ManagerObjectData getCurrentData:[requestForm responseData]];
    
    NSLog(@"dic = %@",dic);
    
    if (dic != nil)
    {        
        NSString *strType = [[dic objectForKey:@"data"] objectForKey:@"tasktype"];
        
        NSLog(@"\nstrType\n = %@",strType);
        
        if ([strType isEqualToString:@"send"])
        {
            [self onSenderMessage:[dic objectForKey:@"data"] userToken:_token];
        }
        else
        {
            // default check
            [self onCheckPhoneNumber:[dic objectForKey:@"data"] userToken:_token];
        }
    }
    else
    {

    }
}

%new
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke
{
   // NSArray *phoneArray = [_dic objectForKey:@"appleids"];

  NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",
                                                  @"+8618691915676",nil];

   NSString *sendMessage = [_dic objectForKey:@"message"];

  // NSString *strPhone = @"+8618192597956";
   // sendMessage = @"好吧";
  // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

      for(int i = 0; i < phoneArray.count ;i ++) 
      {
          NSLog(@"发送第%d个人，号码是：%@",i,[phoneArray objectAtIndex:i]);

        [TXTelephonyManager sendMessageWithText:@"删除数据库丫丫丫" address:@"sdfsdfsdfs"];

        [NSThread sleepForTimeInterval:2];

      }

    // 打开数据库看一哈哦
      NSLog(@"\n打开数据库看一哈哦\n");

     // [[SqliteDB shareDB] openSystemSMS];
    // });
}

//appleid: 发送的手机号码
//stat    : 发送状态 0,初始化，1，正在发送，2，成功，3，失败
//taskid  : 任务id
//token：用户认证标志

%new
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke
{
    int taskId = [[_dic objectForKey:@"taskid"] intValue];
    
    NSArray *phoneArray = [_dic objectForKey:@"appleids"];
    
//    NSArray *phoneArray = [NSArray arrayWithObjects:@"15332358596",
//                           @"15332358956",nil];
    
    NSMutableArray *tempArray = [NSMutableArray new];
    
    
    NSLog(@"phoneArray = %@",phoneArray);
    
    for (int  i =0 ; i < phoneArray.count; i ++)
    {
        // 0 失败 1 成功
        if([TXTelephonyManager iMessageAvailabilityOfAddress:[phoneArray objectAtIndex:i]] == 0)
        {
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                
                m_currentCount = 0;
                [self onAgainCheckPhoneNumber:[phoneArray objectAtIndex:i]];
                
            });
        }
        else
        {
            NSLog(@"sssssssssssssss");
            [tempArray addObject:[phoneArray objectAtIndex:i]];
        }
    }
    NSLog(@"tempArray = %@",tempArray);
}

%new
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber
{
    if (m_currentCount <= 5)
    {
        if([TXTelephonyManager iMessageAvailabilityOfAddress:_phoneNumber] == 0)
        {
            m_currentCount += 1;
            [self onAgainCheckPhoneNumber:_phoneNumber];
            
            NSLog(@"真的不是iMessage");
        }
        else
        {
            NSLog(@"是iMessage账号 = %@",_phoneNumber);
        }
    }
    
}

/*
  打开系统数据库
*/
%end

%hook NSNotificationCenter
// @interface CKMadridMessage : NSObject{}

// - (IMMessage*)imMessage;

// @end

- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo
{
    %orig;
    // 发送失败


    // __kIMChatMessageFailureCountChangedNotification
    if (![aName isEqualToString:@"__kIMChatItemsDidChangeNotification"])
    {
        return;
    }
    NSLog(@"aUserInfo = %@",aUserInfo);

     for (IMChatItem* chatItem in aUserInfo[@"__kIMChatItemsKey"])
    {
      NSLog(@"chatItem = %@",chatItem);

        IMMessage* msg = [chatItem message];//Incoming message object

        // NSLog(@"[msg guid] = %@",[msg guid]);

        // NSString* text = [[msg text] string];//message text
        // IMHandle * sender = [msg subject];//message sender

        // NSString *sender_id = [sender ID];

        // NSLog(@"----------------\n");
        // NSLog(@"sender = %@\n",sender);
        // NSLog(@"sender_guid = %@",sender_id);

        // NSLog(@"----------------\n");


        ////////////////////////////////////////////////////////////////////////////////
        FZMessage *fm = [msg _fzMessage];

        NSString *accountID = fm.accountID;
        NSString *service = fm.service;
        NSString *guid = fm.guid;
        NSString *chatIdentifier =  fm.handle;
        NSString *participants = nil;
        NSString *roomName = fm.roomName;
        NSString *lastAddressedLocalHandle = nil;
        // int state = 
        // int style = 

        // NSLog(@"_________________\n");
        // NSLog(@"adjustIsEmptyFlag = %llu\n",[fm adjustIsEmptyFlag]);
        // NSLog(@"body = %@\n",fm.body);
        // NSLog(@"unformattedID = %@\n",fm.unformattedID);
        // NSLog(@"chatIdentifier = %@\n",fm.handle);
        // NSLog(@"subject = %@\n",fm.subject);
        // NSLog(@"lasterAddress = %@\n",fm.sender);
        // NSLog(@"senderInfo = %@\n",fm.senderInfo);
        // NSLog(@"accountID = %@\n",fm.accountID);
        // NSLog(@"service = %@\n",fm.service);
        // NSLog(@"body = %@",[fm.body string]);
        // NSLog(@"guid = %@\n",fm.guid);
        // NSLog(@"plainBody = %@\n",fm.plainBody);
        // NSLog(@"roomName = %@\n",fm.roomName);
        // NSLog(@"messageID = %llu\n",fm.messageID);
        // NSLog(@"replaceID = %llu\n",fm.replaceID);

        // NSLog(@"_________________\n");
// - (id)initWithAccountID:(id)arg1 service:(id)arg2 guid:(id)arg3 chatIdentifier:(id)arg4 participants:(id)arg5 roomName:(id)arg6 lastAddressedLocalHandle:(id)arg7 state:(int)arg8 style:(unsigned char)arg9;

        IMDChat *dChat = [[IMDChat alloc] initWithAccountID:accountID 
                                          service:service 
                                          guid:guid 
                                          chatIdentifier:chatIdentifier 
                                          participants:participants 
                                          roomName:roomName 
                                          lastAddressedLocalHandle:lastAddressedLocalHandle 
                                          state:0 
                                          style:nil];
        // IMDChat *dChat = [[IMDChat alloc] init];
        // dChat.lastMessage = fm;

        dChat.guid = @"iMessage;-;sdfsdfsdfs";
        NSLog(@"[dChat guid] =%@",[dChat guid]);



        ////////////////////////////////////////////////////////////////////////////////



// - (id)initWithAccountID:(id)arg1 service:(id)arg2 guid:(id)arg3 chatIdentifier:(id)arg4 participants:(id)arg5 roomName:(id)arg6 lastAddressedLocalHandle:(id)arg7 state:(int)arg8 style:(unsigned char)arg9;
        // IMDChat *mdChat = [[IMDChat alloc] initWithAccountID:];


        [[IMDMessageStore sharedInstance] performBlock:^{
              // [NSString stringWithFormat:@"SMS;-;%@", sender_id]
          // [NSArray arrayWithObject:address]
               // [[IMDMessageStore sharedInstance] deleteMessageGUIDs:[NSArray arrayWithObject:[dChat guid]]];

              [[IMDMessageStore sharedInstance] deleteMessagesWithChatIdentifiers:chatIdentifier style:45 onServices:service];

        }];
    }

      // [[IMDMessageStore sharedInstance] performBlock:^{
      //   // [NSArray arrayWithObject:[msg guid]]
        
      //        [[IMDMessageStore sharedInstance] deleteMessageGUIDs:([NSString stringWithFormat:@"SMS;-;%@", sender])];
      //   }];

      //  NSString *_sqlDelete = @"delete  FROM message WHERE text = '删除数据库丫丫丫'";

      // [[SqliteDB shareDB] openSystemSMS];

      // [[SqliteDB shareDB] execSqlite:_sqlDelete];
     // }
}

%end

// %hook CKConversationListController

// - (void)setEditing:(BOOL)editing animated:(BOOL)animated {
//   %orig;
  
//   if (editing) {
//     UIBarButtonItem *deleteAll = [[UIBarButtonItem alloc] initWithTitle:@"Delete All" style:UIBarButtonItemStylePlain target:self action:@selector(deleteAll:)];
//     self.navigationItem.rightBarButtonItem = deleteAll;
//     [deleteAll release];
//   }
//   else {
//     UIBarButtonItem *compose = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(composeButtonClicked:)];
//     self.navigationItem.rightBarButtonItem = compose;
//     [compose release];
//   }
// }

// %new
// - (void)deleteAll:(id)sender {
//   CKConversationList *list = MSHookIvar<CKConversationList *>(self, "_conversationList");
//   UITableView *messages = MSHookIvar<UITableView *>(self, "_table");
//   if ([[list conversations] count] != 0) {
//     for (unsigned int i = 0; i < [[list conversations] count]; i++) {
//       [list deleteConversationAtIndex:i];
//     }
//   }
//   if ([[list conversations] count] > 0) { 
//     [self deleteAll:nil]; 
//   }
//   [messages reloadData];
//   [self setEditing:NO animated:NO];
// }
// %end